package me.zingon.doc.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Date;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Map;

/**
 * Created by zhidi on 2018-3-27.
 */
public class JwtUtil {

    private final static String KEY = "zingon.ztc";

    private final static Long expire = 20L;

    private final static Logger logger = LoggerFactory.getLogger(JwtUtil.class);

    public static String getToken(Map<String, Object> claims) {
        return getToken(claims,KEY,expire);
    }

    public static String getToken(Map<String,Object> claims,String key,Long mins){
        LocalDateTime now = LocalDateTime.now();
        claims.put("refreshCount", 0);
        String token = Jwts.builder()
                .setIssuedAt(Date.from(now.atZone(ZoneId.systemDefault()).toInstant()))
                .setExpiration(Date.from(now.plusMinutes(mins).atZone(ZoneId.systemDefault()).toInstant()))
                .addClaims(claims)
                .signWith(SignatureAlgorithm.HS256, key)
                .compact();
        return token;
    }

    public static Claims validate(String token) {
        return validate(token,KEY);
    }

    public static Claims validate(String token,String key) {
        try {
            return Jwts.parser().setSigningKey(key).parseClaimsJws(token).getBody();
        } catch (JwtException e) {
            logger.debug(e.toString());
            logger.info("token验证失败");
            return null;
        }
    }

    public static String refresh(Claims claims) {
        logger.info("刷新Token");
        LocalDateTime now = LocalDateTime.now();
        claims.put("refreshCount", (int) claims.get("refreshCount") + 1);
        claims.setExpiration(Date.from(now.plusMinutes(expire).atZone(ZoneId.systemDefault()).toInstant()));
        return Jwts.builder()
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS256, KEY)
                .compact();
    }

}
